package com.Kritsana_Ding.project_ioio;


import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.PrivateKey;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera.Size;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint({ "NewApi", "CommitPrefEdits" })
public class MainActivity extends IOIOActivity implements OnClickListener, OnItemSelectedListener {

	public String get_data = "http://inear3g.embeddednu.com/apis/get_data/evnu2013";
	public String get_location = "http://inear3g.embeddednu.com/apis/get_locations/evnu2013";

    public Spinner spnLable_List;
    public Button btnSubmit;
    public TextView tvShow;
    public TextView tvShow2;
    public String code = "";
    public String msg = "";

    public int index = 0;

    public int startTime = 1 * 1000;
    public int interval = 1 * 1000;
    public int count = 4;
    public int countTime = 0;
    public int countUpdate = 3;
    public int timeUpdate = 5;

    public int oldTime = 1 * 1000;
    public int newTime = 1 * 1000;

    public CountDownTimer cdt;

    public boolean[] num_1 = {
        false, true, false, true, false, true, false, true, false, true
    };
    public boolean[] num_2 = {
        false, false, true, true, false, false, true, true, false, false
    };
    public boolean[] num_3 = {
        false, false, false, false, true, true, true, true, false, false
    };
    public boolean[] num_4 = {
        false, false, false, false, false, false, false, false, true, true
    };

    public boolean digit_0 = true;
    public boolean digit_1 = true;
    public boolean digit_2 = true;
    public boolean digit_3 = true;
    public boolean digit_4 = true;
    public boolean digit_5 = true;
    public boolean digit_6 = true;
    public boolean digit_7 = true;
    public boolean digit_8 = true;
    public boolean digit_9 = true;
    public boolean digit_10 = true;
    public boolean digit_11 = true;
    public boolean digit_12 = true;
    public boolean digit_13 = true;
    public boolean digit_14 = true;
    public boolean digit_15 = true;
    public boolean digit_16 = true;

    public int w = 0;
    public int x = 0;
    public int y = 0;
    public int z = 0;

    public boolean onCreate = true;
    public boolean onPause = false;

    ArrayList < String > ArrayLabel = new ArrayList < String > ();

    Handler h = new Handler();

    public int Timer = 0;

    public boolean run1 = false;
    public boolean run2 = false;
    public boolean run3 = false;
    public boolean internet = false;

    public Handler handler1 = new Handler();
    public Handler handler2 = new Handler();
    public Handler handler3 = new Handler();
    
    
    public int onClick = 0;
    
    public int size = 0;

    public static final String PREFS_NAME = "MyPrefsFile";


    public Runnable task1 = new Runnable() {
        public void run() {
            // TODO Auto-generated method stub  
            if (run1) {
            	createIOIOLooper() ;
            	
                handler1.postDelayed(this, 1000);
                count++;
                countTime++;
                int timeServer = newTime - countTime;
                String sec = Integer.toString(timeServer % 60);
                String min = Integer.toString(timeServer / 60);
                
                

                if (min.length() == 1) {
                    min = "0" + min;
                }
                if (sec.length() == 1) {
                    sec = "0" + sec;
                }

                w = Integer.parseInt(min.charAt(0) + "");
                x = Integer.parseInt(min.charAt(1) + "");

                y = Integer.parseInt(sec.charAt(0) + "");
                z = Integer.parseInt(sec.charAt(1) + "");
                
                
                

                if (timeServer > 0 && size > 0) {
                	
                	toIOIOLED();
                	
                    //showNotification();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            tvShow.setText("" + w + "" + x + " : " + y + "" + z);
                            //showNotification("Run");
                            Log.i("MainActivity Time", "" + w + "" + x + " : " + y + "" + z);
                        }
                    });
                } else {
                    run1 = false;
                    run2 = true;
                    run3 = true;

                    w = 0;
                    x = 0;
                    y = 0;
                    z = 0;
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            tvShow.setText("" + w + "" + x + " : " + y + "" + z);
                            tvShow2.setText(Integer.toString(newTime));
                        }
                    });
                    handler3.postDelayed(task3, 1000);
                }
            }
        }
    };


    public Runnable task2 = new Runnable() {
        public void run() {
            // TODO Auto-generated method stub          
            if (run2) {
                handler2.postDelayed(this, 100);
                if (count == timeUpdate) {
                    count = 0;
                    int tmp = get_time(index);
                    tvShow2.setText(Integer.toString(tmp));
                    
					try {
						size = getJSONfromList(get_location);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    Log.i("MainActivity Task 2", "" + size);
                    if (oldTime != tmp && tmp > 0 && size > 0) {
                        oldTime = tmp;
                        newTime = tmp;
                        countTime = 0;
                    } else if (tmp <= 0) {
                        run1 = false;
                        run2 = true;
                        run3 = true;
                        
                        zero();
                      
                        handler3.postDelayed(task3, 100);
                    }
                }
            }
        }
    };

    public Runnable task3 = new Runnable() {
        public void run() {
            // TODO Auto-generated method stub          
            if (run3) {
                handler3.postDelayed(this, 1000);
                countUpdate++;
                
				
                
                Log.i("MainActivity Task 3", "" + size);
                if (countUpdate == timeUpdate) {
                    countUpdate = 0;
                    
                    try {
    					size = getJSONfromList(get_location);
    				} catch (JSONException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
                    
                    
                    newTime = get_time(index);
                    if (oldTime != newTime && newTime > 0 && size > 0) {
                        oldTime = newTime;
                        countTime = 0;
                        count = 0;
                        run1 = true;
                        run2 = true;
                        run3 = false;
                        handler2.postDelayed(task2, 100);
                        handler1.postDelayed(task1, 1000);

                    }
                    else{
                    	
                    }
                }

                w = 0;
                x = 0;
                y = 0;
                z = 0;
                
                toIOIOLED();



                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        tvShow.setText("" + w + "" + x + " : " + y + "" + z);
                        tvShow2.setText("Wait Server " + Integer.toString(countUpdate) + "\n" + newTime);
                    }
                });

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        start();
        checkInternet();
        
        onPause = false;
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("onPauseMode", onPause);
        editor.commit();
        
        
        stopService(new Intent(this, MyService.class));
        //startService(new Intent(this, MyService.class));
        // showNotification();

    }



    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        showNotification("onStop");
        Log.i("MainActivity Run ", "onStop");
        run1 = false;
        run2 = false;
        run3 = false;
        
        //handler1.postDelayed(task1, 100);
        //handler2.postDelayed(task2, 100);
        //handler3.postDelayed(task3, 100);
        startService(new Intent(this, MyService.class));
        
    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        showNotification("onRestart");
        Log.i("Run ", "onRestart");
        
        run1 = true;
        run2 = true;
        handler1.postDelayed(task1, 1000);
        handler2.postDelayed(task2, 100);
        
        
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
    	super.onResume();
    	
    	//startService(new Intent(this, MyService.class));
    	
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        int indexMode = settings.getInt("indexMode", 0);
        index = indexMode;
        spnLable_List.setSelection(index);
        showNotification("onResume");
        Log.i("MainActivity Run ", "onResume");
        
        if(onClick > 0){
        	run1 = true;
            run2 = true;
            spnLable_List.setEnabled(false);
            //handler1.postDelayed(task1, 1000);
            //handler2.postDelayed(task2, 100);
        }
        stopService(new Intent(this, MyService.class));
    }
    
    



    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
        showNotification("onPause");
        Log.i("MainActivity Run ", "onPause");
	}
    
    
    
    @Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		stopService(new Intent(this, MyService.class));
		LogI("MainActivity onBackPressed", "onBackPressed");
		
	}



	public void zero(){
    	w = 0;
    	x = 0;
    	y = 0;
    	z = 0;
    	toIOIOLED();
    }
    
    



	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
        showNotification("onDestroy");
        Log.i("MainActivity Run ", "onDestroy");
        //startService(new Intent(this, MyService.class));
        stopService(new Intent(this, MyService.class));
        //AppExit();
	}



	@Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (checkInternet()) {
            JSONObject data = null;
            try {
                data = json(get_data);
                code = data.getString("code");
                msg = data.getString("msg");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            int size = 0;
            try {
                size = data.getJSONArray("data_list").length();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            tvShow.setText("Code : " + code + "\n");
            // "Msg  : " + msg + "\n");
            
            

            if (code.equals("0")) {
                if (onCreate) {
                    try {
                        for (int i = 0; i < size; i++) {
                            ArrayLabel.add(data.getJSONArray("data_list").optJSONObject(i).getString("label"));
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }

                    spnLable_List.setOnItemSelectedListener(this);
                    ArrayAdapter < String > arrStart = new ArrayAdapter < String > (MainActivity.this, android.R.layout.simple_spinner_item, ArrayLabel);
                    arrStart.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spnLable_List.setAdapter(arrStart);
                    //spnLable_List.performClick();
                    onCreate = false;
                    
                    stopService(new Intent(this, MyService.class));
                }

                btnSubmit.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        if(onClick % 2 == 0){
                        	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putInt("indexMode", index);
                            editor.putBoolean("onPauseMode", false);
                            // Commit the edits!
                            editor.commit();
                            spnLable_List.setEnabled(false);
                            btnSubmit.setText("Cancel");
                            run1 = true;
                            run2 = true;
                            handler1.postDelayed(task1, 1000);
                            handler2.postDelayed(task2, 100);
                            
                        }
                        else{
                        	run1 = false;
                        	run2 = false;
                        	run3 = false;
                        	spnLable_List.setEnabled(true);
                        	btnSubmit.setText("Submit");
                        }
                        onClick++;
                    }
                });

            } else {
                tvShow.setText("Error");
            }
        }
    }

    public void showNotification(String data) {

        // define sound URI, the sound to be played when there's a notification
       // Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // intent triggered, you can add other intent for other actions
        //Intent intent = new Intent(MainActivity.this, MainActivity.class);
        //PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

        // this is it, we'll build the notification!
        // in the addAction method, if you don't want any icon, just set the first param to 0
        Notification mNotification = new Notification.Builder(this)

            .setContentTitle("iNear")
            .setContentText(data + " : " + w + "" + x + " : " + y + "" + z)
            .setSmallIcon(R.drawable.ninja)
            .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // If you want to hide the notification after it was selected, do the code below
        // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, mNotification);
    }

    public void cancelNotification(int notificationId) {

        if (Context.NOTIFICATION_SERVICE != null) {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
            nMgr.cancel(notificationId);
        }
    }


    private void start() {
        // TODO Auto-generated method stub
        spnLable_List = (Spinner) findViewById(R.id.spinner);
        btnSubmit = (Button) findViewById(R.id.buttonSubmit);
        tvShow = (TextView) findViewById(R.id.textViewTime);
        tvShow2 = (TextView) findViewById(R.id.textViewShow2);
    }


    public boolean checkInternet() {
        ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected() == true) {
            //Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
            return true;
        } else {
            Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
            return false;
        }
    }

    public String getJSONUrl(String urls) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urls);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                //                              Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    public JSONObject json(String url) throws JSONException {
        JSONObject mainJson = new JSONObject(getJSONUrl(url));
        mainJson.getString("code");
        mainJson.getString("msg");
        JSONArray jsonArray = mainJson.getJSONArray("data_list");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject objJson = jsonArray.getJSONObject(i);
            objJson.getString("distance");
            objJson.getString("date");
            objJson.getString("time");
            objJson.getString("timenow");
            objJson.getString("label");
        }
        return mainJson;
    }

    public int get_time(int i) {
        String times = "1";
        JSONObject datas = new JSONObject();
        try {
            datas = json(get_data);
            times = datas.getJSONArray("data_list").optJSONObject(i).getString("time");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        double t = Double.parseDouble(times);
        return (int) t;
    }
    

    
    public int getJSONfromList(String url) throws JSONException {
        JSONObject mainJson = new JSONObject(getJSONUrl(url));
        mainJson.getString("code");
        mainJson.getString("msg");
        JSONArray jsonArray = mainJson.getJSONArray("location_list");
        
        Log.i("getJSONfromList", jsonArray.length() + "");

        return jsonArray.length();
    }

    public void toIOIOLED() {
        if (z % 2 == 0) {
            digit_0 = false;
        } else {
            digit_0 = true;
        }

        digit_1 = num_1[z];
        digit_2 = num_2[z];
        digit_3 = num_3[z];
        digit_4 = num_4[z];

        digit_5 = num_1[y];
        digit_6 = num_2[y];
        digit_7 = num_3[y];
        digit_8 = num_4[y];

        digit_9 = num_1[x];
        digit_10 = num_2[x];
        digit_11 = num_3[x];
        digit_12 = num_4[x];

        digit_13 = num_1[w];
        digit_14 = num_2[w];
        digit_15 = num_3[w];
        digit_16 = num_4[w];

    }

    class Looper extends BaseIOIOLooper {

        public DigitalOutput led_0;
        public DigitalOutput led_1;
        public DigitalOutput led_2;
        public DigitalOutput led_3;
        public DigitalOutput led_4;
        public DigitalOutput led_5;
        public DigitalOutput led_6;
        public DigitalOutput led_7;
        public DigitalOutput led_8;
        public DigitalOutput led_9;
        public DigitalOutput led_10;
        public DigitalOutput led_11;
        public DigitalOutput led_12;
        public DigitalOutput led_13;
        public DigitalOutput led_14;
        public DigitalOutput led_15;
        public DigitalOutput led_16;

        @Override
        protected void setup() throws ConnectionLostException,
        InterruptedException {
            // TODO Auto-generated method stub

            led_0 = ioio_.openDigitalOutput(0, true);

            led_1 = ioio_.openDigitalOutput(1, true);
            led_2 = ioio_.openDigitalOutput(2, true);
            led_3 = ioio_.openDigitalOutput(3, true);
            led_4 = ioio_.openDigitalOutput(4, true);

            led_5 = ioio_.openDigitalOutput(5, true);
            led_6 = ioio_.openDigitalOutput(6, true);
            led_7 = ioio_.openDigitalOutput(7, true);
            led_8 = ioio_.openDigitalOutput(8, true);

            led_9 = ioio_.openDigitalOutput(9, true);
            led_10 = ioio_.openDigitalOutput(10, true);
            led_11 = ioio_.openDigitalOutput(11, true);
            led_12 = ioio_.openDigitalOutput(12, true);

            led_13 = ioio_.openDigitalOutput(13, true);
            led_14 = ioio_.openDigitalOutput(14, true);
            led_15 = ioio_.openDigitalOutput(15, true);
            led_16 = ioio_.openDigitalOutput(16, true);


            runOnUiThread(new Runnable() {@Override
                public void run() {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), "Connect IOIO Board", Toast.LENGTH_LONG).show();
                }
            });
        }

        @Override
        public void loop() throws ConnectionLostException, InterruptedException {
            // TODO Auto-generated method stub

            led_0.write(digit_0);

            led_1.write(digit_1);
            led_2.write(digit_2);
            led_3.write(digit_3);
            led_4.write(digit_4);

            led_5.write(digit_5);
            led_6.write(digit_6);
            led_7.write(digit_7);
            led_8.write(digit_8);

            led_9.write(digit_9);
            led_10.write(digit_10);
            led_11.write(digit_11);
            led_12.write(digit_12);

            led_13.write(digit_13);
            led_14.write(digit_14);
            led_15.write(digit_15);
            led_16.write(digit_16);

            Log.i("LED", "on/off");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {

            }
        }

    }

    public IOIOLooper createIOIOLooper() {
    	
        return new Looper();
    }

    @Override
    public void onItemSelected(AdapterView <? > arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        spnLable_List.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView <? > parent, View v, int position, long id) {
                // TODO Auto-generated method stub
                index = position;
            }

            @Override
            public void onNothingSelected(AdapterView <? > arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    @Override
    public void onNothingSelected(AdapterView <? > arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
    }
    
    public void AppExit(){
	    //this.finish();
		
	    Intent intent = new Intent(Intent.ACTION_MAIN);
	    intent.addCategory(Intent.CATEGORY_HOME);
	    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);	    
	    startActivity(intent);
		finish();
		System.exit(0);
	}
    
    public void LogI(String a, String b){
    	Log.i(a,b);
    }
    
    
}